package formes;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ca.etsmtl.log.util.IDLogger;

/**
 * Gere la creation des formes <br \>
 * Cette classe implémente le pattern singleton.
 * 
 * @author Sebastien
 * 
 */

public class FormeCreator
{
    private static final String LIGNE = "LIGNE";
    private static final String CARRE = "CARRE";
    private static final String RECTANGLE = "RECTANGLE";
    private static final String CERCLE = "CERCLE";
    private static final String OVALE = "OVALE";
    private static final FormeCreator INSTANCE = new FormeCreator();
        
    private static IDLogger logger; 

    private FormeCreator()
    {
		logger = IDLogger.getInstance();
    }

    /**
     * Retorune l'instance du singleton
     * 
     * @return instance
     */
    public static FormeCreator getInstance()
    {
        return FormeCreator.INSTANCE;
    }

    /**
     * Cree la forme a partir d'une chaine du seveur
     * 
     * @param information
     *            String du serveur
     * @return la forme
     */
    public static Forme createForme(String information)
    {
        Forme shape;
        ArrayList<String> info = DivideString(information);
        
        if (info.get(1).equals(LIGNE)) {
            shape = new Ligne(info);
        } else if (info.get(1).equals(CARRE)) {
            shape = new Carre(info);
        } else if (info.get(1).equals(RECTANGLE)) {
            shape = new Rectangle(info);
        } else if (info.get(1).equals(CERCLE)) {
            shape = new Cercle(info);
        } else if (info.get(1).equals(OVALE)) {
            shape = new Ovale(info);
        } else {
            shape = null;
        }
        
        logger.logID(shape.getId());

        return shape;
    }

    /**
     * divise le string dans un arraylist
     * 
     * @param information
     *            String du serveur
     * @return arraylist contenant le string divisé
     */
    private static ArrayList<String> DivideString(String information)
    {
        String tableauChaine[] = null;
        ArrayList<String> info = new ArrayList<String>();
        // base du code provenant de
        // https://cours.etsmtl.ca/log121/private/pboucher/
        Pattern p = Pattern.compile("(\\d+) <(.*)> (.*) </\\2>");
        Matcher m = p.matcher(information);
        
        while (m.find()) {
            info.add(m.group(1));
            info.add(m.group(2));
            tableauChaine = m.group(3).split(" ");

            for (int i = 0; i < tableauChaine.length; ++i) {
                info.add(tableauChaine[i]);
            }
        }

        return info;
    }

}
